package com.lsl.test1;

import org.junit.Test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author lishuailong
 * @create 2020-07-10 17:11
 */
public class UDPtest3 {

    /**
     * 发送端
     */
    @Test
    public void sending() throws IOException {
        DatagramSocket socket = new DatagramSocket();

        String s="我是垃圾短信！";
        byte[] data = s.getBytes();
        DatagramPacket packet = new DatagramPacket(data,0,data.length, InetAddress.getLocalHost(),9090);
        socket.send(packet);

        socket.close();
    }

    /**
     * 接收端
     */
    @Test
    public void receiver() throws IOException {
        DatagramSocket socket = new DatagramSocket(9090);

        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length );
        socket.receive(packet);
        String string = new java.lang.String(packet.getData(),0,packet.getLength());
        System.out.println(string);
        socket.close();
    }
}
